/*
 * =====================================================================================
 *
 *       Filename:  app_test.c
 *
 *    Description:  字符设备并发控制测试类
 *    通过fork()接口，让父进程和子进程都去访问同一个字符设备文件进行写操作
 *
 *        Version:  1.0
 *        Created:  2015年09月18日 04时17分36秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */


#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    int fd , ret;
    char buf[256];
    printf("Two processes are writing ...\n");
    if(-1 == (ret = fork())){
        printf("fork() failed error\n");
        perror("fork()");
        _exit(EXIT_FAILURE);
    }else if (0 == ret){
        //子进程操作
        if(-1 == (fd == open("/dev/memdev0",O_RDWR))){
            printf("open() error");
            _exit(EXIT_FAILURE);
        }
        strcpy(buf,"Here is the CHILD writing ..");
        printf("Child write:%s\n",buf);
        write(fd,buf , strlen(buf));
        close(fd); 
        _exit(EXIT_SUCCESS); 
    }else
    {
        //父进程操作
        if(-1 == (fd = open("/dev/memdev0",O_RDWR))){
            printf("open() error");
            _exit(EXIT_FAILURE);
        }
        strcpy(buf,"The semaphore is nesessory in the memdev driver ..");
        printf("Father write:%s\n",buf);
        write(fd,buf,strlen(buf));

        close(fd);
        wait(NULL); 
    } 
    if(-1 == (fd =open("/dev/memdev0",O_RDWR))){
            printf("open() error");
            _exit(EXIT_FAILURE);
    }
    memset(buf,0,sizeof(buf));
    read(fd , buf,sizeof(buf));
    printf("At laste , the content in memdev is :%s\n", buf); 
    close(fd); 
    return 0;
}
